const validate = require("./validate.js");
import __config from "@/config/env";
const formatTime = (date) => {
	const year = date.getFullYear();
	const month = date.getMonth() + 1;
	const day = date.getDate();
	const hour = date.getHours();
	const minute = date.getMinutes();
	const second = date.getSeconds();
	return (
		[year, month, day].map(formatNumber).join("/") +
		" " +
		[hour, minute, second].map(formatNumber).join(":")
	);
};
const timestampToTime = (timestamp) => {
	var date = new Date(timestamp);
	var Y = date.getFullYear() + "-";
	var M = (date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1) + "-";
	var D = (date.getDate() < 10 ? "0" + date.getDate() : date.getDate()) + " ";
	var h = (date.getHours() < 10 ? "0" + date.getHours() : date.getHours()) + ":";
	var m = (date.getMinutes() < 10 ? "0" + date.getMinutes() : date.getMinutes()) + ":";
	var s = date.getSeconds() < 10 ? "0" + date.getSeconds() : date.getSeconds();
	return Y + M + D + h + m + s;
};
const formatNumber = (n) => {
	n = n.toString();
	return n[1] ? n : "0" + n;
};
//空值过滤器

const filterForm = (form) => {
	let obj = {};
	Object.keys(form).forEach((ele) => {
		if (!validate.validatenull(form[ele])) {
			obj[ele] = form[ele];
		}
	});
	return obj;
};
//获取当前页面带参数的url
const getCurrentPageUrlWithArgs = (val) => {
	const pages = getCurrentPages();
	const currentPage = pages[pages.length - 1];
	const url = currentPage.route;
	const options = currentPage.options;
	let urlWithArgs = `/${url}?`;

	for (let key in options) {
		const value = options[key];
		urlWithArgs += `${key}=${value}&`;
	}

	urlWithArgs = urlWithArgs.substring(0, urlWithArgs.length - 1);
	return urlWithArgs;
};
//获取url中的参数
const getUrlParam = (path, name) => {
	var reg = new RegExp("(^|\\?|&)" + name + "=([^&]*)(\\s|&|$)", "i");
	if (reg.test(path)) return unescape(RegExp.$2.replace(/\+/g, " "));
	return "";
};
//判断是否为微信浏览器中运行
const isWeiXinBrowser = () => {
	// #ifdef H5
	// window.navigator.userAgent属性包含了浏览器类型、版本、操作系统类型、浏览器引擎类型等信息，这个属性可以用来判断浏览器类型
	let ua = window.navigator.userAgent.toLowerCase();
	// 通过正则表达式匹配ua中是否含有MicroMessenger字符串
	if (ua.match(/MicroMessenger/i) == "micromessenger") {
		return true;
	} else {
		return false;
	}
	// #endif
	return false;
};
//判断是否是小程序
const isMiniPg = () => {
	let isMiniPg = false;
	//#ifdef MP-WEIXIN
	isMiniPg = true;
	//#endif
	return isMiniPg;
};
//获取客服端代码
const getClientCode = () => {
	let code = {};
	//#ifdef MP-WEIXIN
	code = {
		key: "MP-WEIXIN",
		value: "微信小程序",
	};
	//#endif
	//#ifdef H5
	//普通H5
	code = {
		key: "H5",
		value: "普通H5",
	};
	if (isWeiXinBrowser()) {
		//微信公众号H5
		code = {
			key: "H5-WX",
			value: "公众号H5",
		};
	}
	//#endif
	return code;
};
//重置url中的参数
const resetPageUrl = (query) => {
	var ary = [];
	for (var p in query) {
		if (query.hasOwnProperty(p) && query[p]) {
			ary.push(encodeURIComponent(p) + "=" + encodeURIComponent(query[p]));
		}
	}
	if (ary.length > 0) {
		let url = "?" + ary.join("&");
		history.replaceState(history.state, null, url); //替换页面显示url
	}
};

const imgUrlToBase64 = (imageUrl) => {
	return new Promise((resolve, reject) => {
		try {
			uni.downloadFile({
				url: imageUrl + "?s=" + Math.random().toString(),
				success: (res) => {
					if (res.statusCode === 200) {
						// uni 如果是H5或者APP会自动转为base64返回
						resolve(res.tempFilePath);
					} else {
						reject(res.errMsg);
					}
				},
				fail(err) {
					reject(err);
				},
			});
		} catch (e) {
			console.log(e);
			resolve(imageUrl);
		}
	});
};

// 设置原生app的分享url为h5的地址url
const setAppPlusShareUrl = (query) => {
	const pages = getCurrentPages();
	const curPage = pages[pages.length - 1];
	const userInfo = uni.getStorageSync("user_info");
	const userCode = userInfo ? userInfo.userCode : "";
	let component_appid = "";
	if (query && query.componentAppId) {
		component_appid = "&component_appid=" + query.componentAppId;
	}
	let fullPath = curPage.$page.fullPath;
	//判断是否有问号
	fullPath = fullPath.indexOf("?") != -1 ? fullPath + "&" : fullPath + "?";
	if (userCode) {
		return (
			__config.h5HostUrl +
			fullPath +
			"tenant_id=" +
			__config.tenantId +
			"&app_id=" +
			__config.wxAppId +
			"&sharer_user_code=" +
			userCode +
			component_appid
		);
	} else {
		return (
			__config.h5HostUrl +
			fullPath +
			"tenant_id=" +
			__config.tenantId +
			"&app_id=" +
			__config.wxAppId +
			component_appid
		);
	}
};

// 设置原生app的分享url为h5的地址url（用于分销，默认首页地址）
const setAppPlusHomeShareUrl = (query) => {
	const userInfo = uni.getStorageSync("user_info");
	const userCode = userInfo ? userInfo.userCode : "";
	let component_appid = "";
	if (query && query.componentAppId) {
		component_appid = "&component_appid=" + query.componentAppId;
	}
	let fullPath = "/pages/home/index?";
	if (userCode) {
		return (
			__config.h5HostUrl +
			fullPath +
			"tenant_id=" +
			__config.tenantId +
			"&app_id=" +
			__config.wxAppId +
			"&sharer_user_code=" +
			userCode +
			component_appid
		);
	} else {
		return (
			__config.h5HostUrl +
			fullPath +
			"tenant_id=" +
			__config.tenantId +
			"&app_id=" +
			__config.wxAppId +
			component_appid
		);
	}
};

// 设置h5的分享地址url
const setH5ShareUrl = (val) => {
	const userInfo = uni.getStorageSync("user_info");
	const userCode = userInfo ? userInfo.userCode : "";
	let url = window.location.href;
	// 如果没有 sharer_user_code 就添加，如果有就替换为自己的userCode
	if (userCode) {
		let index = url.indexOf("&sharer_user_code=");
		if (index == -1) {
			url = url + "&sharer_user_code=" + userCode;
		} else {
			let urlTemp = url.slice(0, index);
			url = urlTemp + "&sharer_user_code=" + userCode;
		}
	}
	return url;
};

// 设置H5的分享url（用于分销，默认首页地址）
const setH5HomeShareUrl = (val) => {
	const userInfo = uni.getStorageSync("user_info");
	const userCode = userInfo ? userInfo.userCode : "";
	// 如果没有 sharer_user_code 就添加
	let url = window.location.origin + window.location.search;
	if (userCode) {
		let index = url.indexOf("&sharer_user_code=");
		if (index == -1) {
			url = url + "&sharer_user_code=" + userCode;
		} else {
			let urlTemp = url.slice(0, index);
			url = urlTemp + "&sharer_user_code=" + userCode;
		}
	}
	return url;
};
// 获取当前页面路由或 path
const getCurPage = (pages) => {
	let curPage = pages[pages.length - 1];
	return curPage.route;
};
// 保存别人分享来的 userCode
const saveSharerUserCode = (options) => {
	if (options.scene) {
		//接受二维码中参数
		/**
		 * 这里需要特别注意：
		 * 由于腾讯限制了scenes的长度，导致传参的局限性，为尽可能的利用这有限的长度传参，
		 * 故我们定义了scenes的参数格式，当一个页面需要传多个参数时，我们用“&”符号分割开来，第2位固定放分享人的user_code，这样可以最大限度减少长度占用
		 * 第1位一般放ID，第2位固定放分享人的user_code，比如商品页面scenes为：goodspuId+&+sharer_user_code
		 * 因为固定第2位放分享人的user_code，当有些页面无需传ID时，我们也需要用“&”拼一下，第一位随意用一个字符点位即可，比如页面scenes为：0+&+sharer_user_code
		 */
		let scenes = decodeURIComponent(options.scene).split("&");
		if (scenes[1]) {
			uni.setStorageSync("sharer_user_code", scenes[1]);
		}
	} else {
		if (options.sharer_user_code) {
			uni.setStorageSync("sharer_user_code", "");
			uni.setStorageSync("sharer_user_code", options.sharer_user_code);
		}
	}
};

// 如果有分享人则给data带上分享人的user_code
const dataAddSharerUserCode = (data) => {
	let sharer_user_code = uni.getStorageSync("sharer_user_code");
	if (sharer_user_code) {
		data = Object.assign(
			{
				sharerUserCode: sharer_user_code,
			},
			data,
		);
	}
	return data;
};
//跳转方法
const goUrl = (url, mode = 1, delta = 1) => {
	// 1:navigateTo 2:redirectTo 3:switchTab 4:reLaunch 5:navigateBack
	try {
		// 此处修正ios下有时候不显示tabbar的问题
		if (!isExecuted) {
			uni.showTabBar({
				success: () => {
					isExecuted = true;
				},
			});
		}
	} catch (e) {}
	if (mode == 1) {
		uni.navigateTo({
			url,
		});
	} else if (mode == 2) {
		uni.redirectTo({
			url,
		});
	} else if (mode == 3) {
		uni.switchTab({
			url,
		});
	} else if (mode == 4) {
		uni.reLaunch({
			url,
		});
	} else if (mode == 5) {
		uni.navigateBack({ delta: delta });
	}
};
//返回登录页面
const backLoginPage = (data) => {
	var pages = getCurrentPages(); // 获取页面栈
	var currPage = pages[pages.length - 1]; // 当前页面
	if (currPage) {
		let curParam = currPage.options;
		// 拼接参数
		let reUrl = "/" + currPage.route;
		if (curParam != null) {
			// 拼接参数
			let param = "";
			for (let key in curParam) {
				param += "&" + key + "=" + curParam[key];
			}
			param = param.substr(1);
			reUrl = reUrl + "?" + param;
			reUrl = encodeURIComponent(reUrl);
		}
		uni.reLaunch({
			url: "/pages/login/index?reUrl=" + reUrl,
		});
	}
};

/**
 * 跳转到页面栈中已存在的页面时，直接返回到该页面中去
 */
const goNavigatePage = (url) => {
	const paramsIndex = url.indexOf("?");
	// 要调整的url
	const goUrl = paramsIndex > -1 ? url.substring(0, paramsIndex) : url;
	let delta = 0;
	let hasUrl = false;
	let pages = getCurrentPages();
	pages.reverse().forEach((item) => {
		let page = "/" + item.route;
		if (page == goUrl) {
			hasUrl = true;
			return;
		} else if (!hasUrl) {
			delta++;
		}
	});
	if (hasUrl) {
		uni.navigateBack({
			delta: delta,
		});
	} else {
		uni.navigateTo({
			url: url,
		});
	}
};
const deepClone = (obj, hash = new WeakMap()) => {
	// 日期对象直接返回一个新的日期对象
	if (obj instanceof Date) {
		return new Date(obj);
	}
	//正则对象直接返回一个新的正则对象
	if (obj instanceof RegExp) {
		return new RegExp(obj);
	}
	//如果循环引用,就用 weakMap 来解决
	if (hash.has(obj)) {
		return hash.get(obj);
	}
	// 获取对象所有自身属性的描述
	let allDesc = Object.getOwnPropertyDescriptors(obj);
	// 遍历传入参数所有键的特性
	let cloneObj = Object.create(Object.getPrototypeOf(obj), allDesc);

	hash.set(obj, cloneObj);
	for (let key of Reflect.ownKeys(obj)) {
		if (typeof obj[key] === "object" && obj[key] !== null) {
			cloneObj[key] = deepClone(obj[key], hash);
		} else {
			cloneObj[key] = obj[key];
		}
	}
	return cloneObj;
};
const isNumber = (val) => {
	return typeof val === "number";
};
const regs = {
	//最多两位小数的数字
	reg1: /^(0|[1-9]\d*)(\.\d{1,2})?/,
};
const reportReport = (file) => {
	const blob = new Blob([file.data], {
		type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8",
	}); // new Blob([res])中不加data就会返回下图中[objece objece]内容（少取一层）
	const link = {
		blob: blob,
		filename: file.headers.filename,
	};
	return link;
};
const isEmptyObject = (obj) => {
	for (var key in obj) {
		if (obj.hasOwnProperty(key)) {
			return false;
		}
	}
	return true;
};
// 战狼战队
// 腾飞战队
// 新星战队
// 梦想战队
// 瑞风战队
// 超越战队
// 凌云战队
// 新锐战队
const zhandui = [
	{
		label: "战狼战队",
		value: "战狼战队",
	},
	{
		label: "腾飞战队",
		value: "腾飞战队",
	},
	{
		label: "新星战队",
		value: "新星战队",
	},
	{
		label: "梦想战队",
		value: "梦想战队",
	},
	{
		label: "瑞风战队",
		value: "瑞风战队",
	},
	{
		label: "超越战队",
		value: "超越战队",
	},
	{
		label: "凌云战队",
		value: "凌云战队",
	},
	{
		label: "新锐战队",
		value: "新锐战队",
	},
];
module.exports = {
	isEmptyObject: isEmptyObject,
	deepClone: deepClone,
	isNumber: isNumber,
	formatTime: formatTime,
	filterForm: filterForm,
	getCurrentPageUrlWithArgs: getCurrentPageUrlWithArgs,
	getUrlParam: getUrlParam,
	isWeiXinBrowser: isWeiXinBrowser,
	isMiniPg: isMiniPg,
	resetPageUrl: resetPageUrl,
	getClientCode: getClientCode,
	imgUrlToBase64: imgUrlToBase64,
	setAppPlusShareUrl: setAppPlusShareUrl,
	setH5ShareUrl: setH5ShareUrl,
	getCurPage: getCurPage,
	saveSharerUserCode: saveSharerUserCode,
	dataAddSharerUserCode: dataAddSharerUserCode,
	backLoginPage: backLoginPage,
	setAppPlusHomeShareUrl,
	setH5HomeShareUrl,
	goNavigatePage,
	goUrl,
	timestampToTime,
	zhandui,
};
